#!/bin/bash

# SmartInput 服务管理脚本
# 提供交互式菜单来管理所有服务

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 显示标题
show_header() {
    clear
    print_message $PURPLE "╔══════════════════════════════════════════════════════════════╗"
    print_message $PURPLE "║                    SmartInput 服务管理器                      ║"
    print_message $PURPLE "║                  智能语音输入系统管理工具                      ║"
    print_message $PURPLE "╚══════════════════════════════════════════════════════════════╝"
    print_message $BLUE ""
}

# 显示菜单
show_menu() {
    print_message $CYAN "🛠️  请选择操作:"
    print_message $BLUE ""
    print_message $GREEN "   1) 🚀 启动所有服务"
    print_message $RED "   2) 🛑 停止所有服务"
    print_message $YELLOW "   3) 🔄 重启所有服务"
    print_message $BLUE "   4) 📊 查看服务状态"
    print_message $CYAN "   5) 📄 查看日志"
    print_message $PURPLE "   6) 🧹 清理日志和缓存"
    print_message $BLUE "   7) 🔒 检查 SSL 证书"
    print_message $YELLOW "   8) ❓ 帮助信息"
    print_message $RED "   0) 🚪 退出"
    print_message $BLUE ""
    print_message $CYAN "请输入选项 (0-8): "
}

# 启动服务
start_services() {
    print_message $GREEN "🚀 启动SmartInput服务..."
    print_message $BLUE "================================"
    
    if [ -f "$PROJECT_ROOT/start.sh" ]; then
        bash "$PROJECT_ROOT/start.sh"
    else
        print_message $RED "❌ 启动脚本不存在"
        return 1
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 停止服务
stop_services() {
    print_message $RED "🛑 停止SmartInput服务..."
    print_message $BLUE "================================"
    
    if [ -f "$PROJECT_ROOT/stop.sh" ]; then
        bash "$PROJECT_ROOT/stop.sh"
    else
        print_message $RED "❌ 停止脚本不存在"
        return 1
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 重启服务
restart_services() {
    print_message $YELLOW "🔄 重启SmartInput服务..."
    print_message $BLUE "================================"
    
    if [ -f "$PROJECT_ROOT/restart.sh" ]; then
        bash "$PROJECT_ROOT/restart.sh"
    else
        print_message $RED "❌ 重启脚本不存在"
        return 1
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 查看状态
show_status() {
    print_message $BLUE "📊 SmartInput服务状态..."
    print_message $BLUE "================================"
    
    if [ -f "$PROJECT_ROOT/status.sh" ]; then
        bash "$PROJECT_ROOT/status.sh"
    else
        print_message $RED "❌ 状态检查脚本不存在"
        return 1
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 查看日志
show_logs() {
    print_message $CYAN "📄 查看日志文件..."
    print_message $BLUE "================================"
    
    local logs_dir="$PROJECT_ROOT/logs"
    
    if [ ! -d "$logs_dir" ]; then
        print_message $YELLOW "⚠️  日志目录不存在: $logs_dir"
        print_message $YELLOW "按任意键继续..."
        read -n 1
        return
    fi
    
    print_message $BLUE "选择要查看的日志:"
    print_message $GREEN "   1) WebSocket服务器日志"
    print_message $BLUE "   2) 移动端应用日志"
    print_message $CYAN "   3) 查看所有日志文件"
    print_message $RED "   0) 返回主菜单"
    print_message $BLUE ""
    print_message $CYAN "请输入选项 (0-3): "
    
    read -n 1 log_choice
    echo ""
    
    case $log_choice in
        1)
            if [ -f "$logs_dir/server.log" ]; then
                print_message $GREEN "📄 WebSocket服务器日志 (最后50行):"
                print_message $BLUE "================================"
                tail -50 "$logs_dir/server.log"
            else
                print_message $YELLOW "⚠️  服务器日志文件不存在"
            fi
            ;;
        2)
            if [ -f "$logs_dir/mobile.log" ]; then
                print_message $GREEN "📄 移动端应用日志 (最后50行):"
                print_message $BLUE "================================"
                tail -50 "$logs_dir/mobile.log"
            else
                print_message $YELLOW "⚠️  移动端日志文件不存在"
            fi
            ;;
        3)
            print_message $GREEN "📄 所有日志文件:"
            print_message $BLUE "================================"
            ls -la "$logs_dir/" 2>/dev/null || print_message $YELLOW "⚠️  无法列出日志文件"
            ;;
        0)
            return
            ;;
        *)
            print_message $RED "❌ 无效选项"
            ;;
    esac
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 清理日志和缓存
cleanup() {
    print_message $PURPLE "🧹 清理日志和缓存..."
    print_message $BLUE "================================"
    
    print_message $YELLOW "⚠️  这将删除所有日志文件和缓存，确定要继续吗? (y/N): "
    read -n 1 confirm
    echo ""
    
    if [[ $confirm =~ ^[Yy]$ ]]; then
        # 清理日志文件
        if [ -d "$PROJECT_ROOT/logs" ]; then
            rm -rf "$PROJECT_ROOT/logs"
            print_message $GREEN "✅ 日志文件已清理"
        fi
        
        # 清理PID文件
        if [ -d "$PROJECT_ROOT/.pids" ]; then
            rm -rf "$PROJECT_ROOT/.pids"
            print_message $GREEN "✅ PID文件已清理"
        fi
        
        # 清理node_modules缓存
        print_message $BLUE "🧹 清理依赖缓存..."
        if [ -d "$PROJECT_ROOT/server/node_modules" ]; then
            print_message $YELLOW "   清理服务器依赖缓存..."
            rm -rf "$PROJECT_ROOT/server/node_modules"
        fi
        
        if [ -d "$PROJECT_ROOT/admin-panel/node_modules" ]; then
            print_message $YELLOW "   清理管理后台依赖缓存..."
            rm -rf "$PROJECT_ROOT/admin-panel/node_modules"
        fi
        
        if [ -d "$PROJECT_ROOT/mobile-app/node_modules" ]; then
            print_message $YELLOW "   清理移动端依赖缓存..."
            rm -rf "$PROJECT_ROOT/mobile-app/node_modules"
        fi
        
        print_message $GREEN "✅ 清理完成"
    else
        print_message $BLUE "取消清理操作"
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 检查 SSL 证书
check_ssl_certs() {
    print_message $BLUE "🔒 检查 SSL 证书..."
    print_message $BLUE "================================"
    
    if [ -f "$PROJECT_ROOT/check-ssl-certs.sh" ]; then
        bash "$PROJECT_ROOT/check-ssl-certs.sh"
    else
        print_message $RED "❌ SSL 证书检查脚本不存在"
        return 1
    fi
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 显示帮助信息
show_help() {
    print_message $CYAN "❓ SmartInput 帮助信息"
    print_message $BLUE "================================"
    print_message $GREEN "🎯 SmartInput 是一个跨平台语音输入系统"
    print_message $BLUE ""
    print_message $BLUE "📋 系统组件:"
    print_message $BLUE "   🖥️  WebSocket服务器 (端口3001) - 负责设备通信和消息路由"
    print_message $BLUE "   📱 移动端PWA应用 (端口3000/3002) - 语音输入界面"
    print_message $BLUE "   🛠️  管理后台 (端口3000) - 设备管理和监控界面"
    print_message $BLUE "   �� 浏览器扩展 - 网页文字注入功能"
    print_message $BLUE ""
    print_message $BLUE "🛠️  管理脚本:"
    print_message $BLUE "   ./start.sh    - 启动所有服务"
    print_message $BLUE "   ./stop.sh     - 停止所有服务"
    print_message $BLUE "   ./restart.sh  - 重启所有服务"
    print_message $BLUE "   ./status.sh   - 查看服务状态"
    print_message $BLUE "   ./manage.sh   - 交互式管理界面"
    print_message $BLUE ""
    print_message $BLUE "📁 重要目录:"
    print_message $BLUE "   ./server/     - WebSocket服务器代码"
    print_message $BLUE "   ./admin-panel/ - 管理后台代码"
    print_message $BLUE "   ./mobile-app/ - 移动端应用代码"
    print_message $BLUE "   ./logs/       - 日志文件目录"
    print_message $BLUE "   ./.pids/      - 进程ID文件目录"
    print_message $BLUE ""
    print_message $BLUE "🔗 访问地址:"
    print_message $BLUE "   WebSocket服务器: https://localhost:3001"
    print_message $BLUE "   移动端应用: http://localhost:3000 或 http://localhost:3002"
    print_message $BLUE "   管理后台: https://localhost:3002"
    print_message $BLUE ""
    print_message $BLUE "🔒 SSL 证书:"
    print_message $BLUE "   所有 HTTPS 服务使用统一的 SSL 证书"
    print_message $BLUE "   证书位置: ./certs/cert.pem 和 ./certs/key.pem"
    print_message $BLUE "   检查证书: 选择菜单选项 7"
    print_message $YELLOW "💡 使用提示:"
    print_message $YELLOW "   1. 首次运行请选择'启动所有服务'"
    print_message $YELLOW "   2. 移动端应用会自动在浏览器中打开"
    print_message $YELLOW "   3. 使用'查看服务状态'来监控系统运行情况"
    print_message $YELLOW "   4. 遇到问题时可以尝试'重启所有服务'"
    
    print_message $BLUE ""
    print_message $YELLOW "按任意键继续..."
    read -n 1
}

# 主循环
main() {
    while true; do
        show_header
        show_menu
        
        read -n 1 choice
        echo ""
        
        case $choice in
            1)
                start_services
                ;;
            2)
                stop_services
                ;;
            3)
                restart_services
                ;;
            4)
                show_status
                ;;
            5)
                show_logs
                ;;
            6)
                cleanup
                ;;
            7)
                check_ssl_certs
                ;;
            8)
                show_help
                ;;
            0)
                print_message $GREEN "👋 感谢使用 SmartInput 服务管理器！"
                exit 0
                ;;
            *)
                print_message $RED "❌ 无效选项，请重新选择"
                sleep 1
                ;;
        esac
    done
}

# 执行主函数
main "$@"
